#include"myStdio.h"


FILE_* fopen_(const char* pathName,const char* mode)
{
    int flag  = 0;
    int defaultMode = 0664;

    if(strcmp(mode,"r")==0)
    {
        flag |= O_RDONLY;
    }
    else if(strcmp(mode,"w")==0)
    {
        flag |= (O_WRONLY | O_CREAT | O_TRUNC);
    }
    else if(strcmp(mode,"a")==0)
    {
        flag |= (O_WRONLY | O_CREAT | O_TRUNC);
        
    }
    else{}

    int fd_ = 0;

    if(flag & O_RDONLY) fd_ = open(pathName,flag);
    else fd_ = open(pathName,flag,defaultMode);
    if(fd_<0)
    {
        const char* err = strerror(errno);
        write(2,err,strlen(err));
        return NULL;//打开文件失败返回NULL
    }
    FILE_ *fp = (FILE_*)malloc(sizeof(FILE_));
    assert(fp);

    fp->flag = REF_LINE;
    fp->fileno = fd_;
    fp->cap = SIZE;
    fp->size = 0;
    memset(fp->buffer,0,SIZE);

    return fp;//打开文件返回一个FILE* fp指针
}

void fwrite_(const void* ptr,int num,FILE_ *fp)
{
    memcpy(fp->buffer+fp->size,ptr,num);
    fp->size +=num;

    //判断是否刷新
    if(fp->flag & REF_NOw)
    {
        write(fp->fileno,fp->buffer,fp->size);
        fp->size = 0;//清空缓冲区
    }
    else if(fp->flag & REF_FULL)
    {
        if(fp->size == fp->cap)
        {
            write(fp->fileno,fp->buffer,fp->size);
            fp->size = 0;
        }
    }
    else if(fp->flag & REF_LINE)
    {
        if(fp->buffer[fp->size-1]=='\n')
        {
            write(fp->fileno,fp->buffer,fp->size);
            fp->size = 0 ;
        }
    }
    else{}

}

void fclose_(FILE_* fp)
{
    fflush_(fp);
    close(fp->fileno);
}

void fflush_(FILE_* fp)
{
    if(fp->size>0)
        write(fp->fileno,fp->buffer,fp->size);
    fsync(fp->fileno);//os强制进行刷新
    fp->size = 0;
}